package org.kazminov.mywakeupper;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

/**
 * Created with IntelliJ IDEA.
 * User: olkazmin
 * Date: 12/1/12
 * Time: 7:32 AM
 * To change this template use File | Settings | File Templates.
 */
public class WakeService extends Service {

    public static final String ACTION_START = "org.kazminov.mywakeupper.ACTION_START";

    public static final String ACTION_SLEEP = "org.kazminov.mywakeupper.ACTION_SLEEP";

    public static final String TAG_WAKE_LOCK = "org.kazminov.mywakeupper.TAG_WAKE_LOCK";

    private static final String TAG = "WakeService";

    private PowerManager.WakeLock mWakeLock;

    private Handler mHandler;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(TAG, "onStartCommand: " +  intent.toString());
        final String action = intent.getAction();


        if (action == null) {
            return Service.START_STICKY;
        }

        final boolean isAlreadyRunning = mHandler != null;
        Log.v(TAG, "onStartCommand: isAlreadyRunning=" + isAlreadyRunning);
        if (!isAlreadyRunning) {
            final HandlerThread thread = new HandlerThread("WakeService thread");
            thread.start();
            mHandler = new Handler(thread.getLooper());
            startEverything();
        }

        if (action.equalsIgnoreCase(WakeEventsReceiver.ACTION_MY_WAKE_UP)) {
            final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (powerManager.isScreenOn()) {
                Log.v(TAG, "onStartCommand: screen is ON, so skipping");
                return Service.START_NOT_STICKY;
            }
            mWakeLock = powerManager.newWakeLock(
                    PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    TAG_WAKE_LOCK);
            mWakeLock.acquire(5000);
        } else if (action.equalsIgnoreCase(ACTION_START)) {
            // Do nothing. We just start and init service above.
        }

        return Service.START_STICKY;
    }

    private void startEverything() {
        Log.v(TAG, "startEverything");
        // Log
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy");
    }
}
